package com.example.graduation.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.graduation.entity.pojo.Image;
import com.example.graduation.service.ImageService;
import com.example.graduation.util.FileUtil;
import com.example.graduation.util.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.io.File;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * @author Jeffery
 * 文件的定时任务
 */
@Configuration
@EnableScheduling
@Slf4j(topic = "FileTask")
public class FileTask {
    @Resource
    private ResourceUtil resourceUtil;
    @Resource
    private FileUtil fileUtil;
    @Resource
    private ImageService imageService;

    /**
     * 每隔5秒，定时将file文件夹下上传的问件存储至数据库，并同时删除file文件夹下对应的文件
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void uploadFile() {
        String filePath = resourceUtil.getFile();
        File file = new File(filePath);
        String imageId = "";
        try {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                //确保file文件夹下存在文件......
//                log.info("resources文件夹下存在文件数量为： {} ,当前时间戳 : {}", files.length, new Timestamp(System.currentTimeMillis()));
                for (File f : files) {
                    String currentFileName = f.getName();
                    int index = currentFileName.lastIndexOf('.');
                    imageId = currentFileName.substring(0, index);
                    byte[] bytes = fileUtil.fileToByte(f);
                    log.info("len : " + bytes.length);
                    QueryWrapper<Image> wrapper = new QueryWrapper<>();
                    wrapper.eq("image_id", imageId);
                    Image image = imageService.getOne(wrapper);
                    if (image != null) {
                        image.setBlog(bytes);
                        imageService.updateById(image);
                        //执行删除文件 by id
                        boolean delete = f.delete();
//                        if (delete) {
//                            log.info("本地文件删除成功 ======= image_id : {}", imageId);
//                        } else {
//                            log.info("本地文件删除失败 ======= image_id : {}", imageId);
//                        }
                    } else {
                        return;
                    }
                }
            }
        } catch (Exception e) {
            log.error("发生异常了：{}", e.getMessage());
        }
    }
}
